package com.yizhiliulianta.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yizhiliulianta.usercenter.exception.BusinessException;
import com.yizhiliulianta.usercenter.model.User;
import com.yizhiliulianta.usercenter.mapper.UserMapper;
import com.yizhiliulianta.usercenter.model.request.userModifyRequest;
import com.yizhiliulianta.usercenter.service.UserService;
import com.yizhiliulianta.usercenter.utils.ErrorCode;
import com.yizhiliulianta.usercenter.utils.UserIdGeneratorUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.yizhiliulianta.usercenter.contant.UserConstan.USER_LOGIN_STATE;

/**
 * @author yizhiliulianta
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-05-01 22:40:17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final String SALT = "yizhiliulianta";

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //判断是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"参数为空");
        }

        //账户长度是否小于4
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"用户账号长度过断");
        }
        //密码或确认密码长度是否小于8
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"用户密码过短");
        }

        //判断账号是否包含特殊字符
        String validPattern = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：\"”“’。，、？]|\n|\r|\t";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"账号含有特殊字符");
        }

        //判断是否密码一致
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"两次密码不相同");
        }

        //账户是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"账号重复");
        }

        //获取唯一用户id
        String durianCode = UserIdGeneratorUtils.getDurianCode();
        //用户编号是否重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("durianCode", durianCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"编号重复");
        }

        //密码加密并保存
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setDurianCode(durianCode);
        user.setUsername("榴莲@"+durianCode);
        int insert = userMapper.insert(user);
        if (insert != 1) {
            throw new BusinessException(ErrorCode.PARANS_ERROR,"注册失败");
        }

        return user.getId();

    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //判断是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        //账户长度是否小于4
        if (userAccount.length() < 4) {
            return null;
        }
        //密码或确认密码长度是否小于8
        if (userPassword.length() < 8) {
            return null;
        }
        //判断账号是否包含特殊字符
        String validPattern = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：\"”“’。，、？]|\n|\r|\t";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //查询失败
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        //用户脱敏
        User safetyUser = getSafetyUser(user);
        //记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    @Override
    public List<User> searchUsers(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(username)) {
            queryWrapper.like("username", username);
        }
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public boolean deleteUser(long id) {
        if (id <= 0) {
            return false;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return this.remove(queryWrapper);
    }

    @Override
    public User getSafetyUser(User orginUser) {
        if (orginUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(orginUser.getId());
        safetyUser.setUsername(orginUser.getUsername());
        safetyUser.setUserAccount(orginUser.getUserAccount());
        safetyUser.setAvatarUrl(orginUser.getAvatarUrl());
        safetyUser.setGender(orginUser.getGender());
        safetyUser.setPhone(orginUser.getPhone());
        safetyUser.setEmail(orginUser.getEmail());
        safetyUser.setDurianCode(orginUser.getDurianCode());
        safetyUser.setUserRole(orginUser.getUserRole());
        safetyUser.setUserStatus(orginUser.getUserStatus());
        safetyUser.setCreateTime(orginUser.getCreateTime());
        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        //移除登录
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public Boolean userModify(userModifyRequest userModifyRequest,HttpServletRequest request) {
        Object ObjUser = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) ObjUser;

        String userAccount = currentUser.getUserAccount();

        String username = userModifyRequest.getUsername();
        if (username==null){
            username = currentUser.getUsername();
        }
        String phone = userModifyRequest.getPhone();
        if (phone==null){
            phone = currentUser.getPhone();
        }
        Integer gender = userModifyRequest.getGender();
        if (gender==null){
            gender = currentUser.getGender();
        }
        String email = userModifyRequest.getEmail();
        if (email==null){
            email = currentUser.getEmail();
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("username",username);
        updateWrapper.set("phone",phone);
        updateWrapper.set("gender",gender);
        updateWrapper.set("email",email);
        updateWrapper.eq("userAccount", userAccount);
        int update = userMapper.update(updateWrapper);
        if (update < 1){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"修改失败");
        }
        return true;
    }
}




